/**
 * 文本操作处理器
 * 处理文本编辑、行操作、缩进、注释等功能
 */
export class TextOperations {
    constructor(editor, options = {}) {
        this.editor = editor
        this.options = {
            tabSize: 4,
            ...options
        }
    }

    /**
     * 处理缩进
     */
    handleIndent() {
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd
        const text = this.editor.editor.value

        if (start === end) {
            // 无选中文本，插入Tab
            const spaces = ' '.repeat(this.options.tabSize)
            this.editor.editor.value = 
                text.substring(0, start) + 
                spaces + 
                text.substring(end)
            this.editor.editor.selectionStart = this.editor.editor.selectionEnd = start + this.options.tabSize
        } else {
            // 有选中文本，缩进选中的行
            this.indentSelectedLines()
        }

        this.editor._updateEditor()
    }

    /**
     * 处理去缩进
     */
    handleOutdent() {
        const text = this.editor.editor.value
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd

        if (start === end) {
            // 单行去缩进
            const lineStart = text.lastIndexOf('\n', start - 1) + 1
            const lineEnd = text.indexOf('\n', start)
            const line = text.substring(lineStart, lineEnd === -1 ? text.length : lineEnd)

            let newLine = line
            if (line.startsWith(' '.repeat(this.options.tabSize))) {
                newLine = line.substring(this.options.tabSize)
            } else if (line.startsWith('\t')) {
                newLine = line.substring(1)
            }

            this.editor.editor.value = text.substring(0, lineStart) + newLine + 
                                      text.substring(lineEnd === -1 ? text.length : lineEnd)

            this.editor.editor.selectionStart = this.editor.editor.selectionEnd = 
                start - (line.length - newLine.length)
        } else {
            // 多行去缩进
            this.outdentSelectedLines()
        }

        this.editor._updateEditor()
    }

    /**
     * 缩进选中的行
     */
    indentSelectedLines() {
        const text = this.editor.editor.value
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd

        const beforeSelection = text.substring(0, start)
        const selection = text.substring(start, end)
        const afterSelection = text.substring(end)

        const lineStart = beforeSelection.lastIndexOf('\n') + 1
        const fullSelection = text.substring(lineStart, end)

        const indentedLines = fullSelection.split('\n').map(line => 
            ' '.repeat(this.options.tabSize) + line
        ).join('\n')

        this.editor.editor.value = text.substring(0, lineStart) + indentedLines + afterSelection

        // 保持选中状态
        this.editor.editor.selectionStart = start + this.options.tabSize
        this.editor.editor.selectionEnd = end + (this.options.tabSize * fullSelection.split('\n').length)
    }

    /**
     * 去缩进选中的行
     */
    outdentSelectedLines() {
        const text = this.editor.editor.value
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd

        const beforeSelection = text.substring(0, start)
        const afterSelection = text.substring(end)

        const lineStart = beforeSelection.lastIndexOf('\n') + 1
        const fullSelection = text.substring(lineStart, end)

        const outdentedLines = fullSelection.split('\n').map(line => {
            if (line.startsWith(' '.repeat(this.options.tabSize))) {
                return line.substring(this.options.tabSize)
            } else if (line.startsWith('\t')) {
                return line.substring(1)
            }
            return line
        }).join('\n')

        this.editor.editor.value = text.substring(0, lineStart) + outdentedLines + afterSelection

        // 保持选中状态
        const reduction = fullSelection.length - outdentedLines.length
        this.editor.editor.selectionStart = Math.max(lineStart, start - this.options.tabSize)
        this.editor.editor.selectionEnd = end - reduction
    }

    /**
     * 删除行
     */
    deleteLine() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lineStart = text.lastIndexOf('\n', pos - 1) + 1
        const lineEnd = text.indexOf('\n', pos)

        const newText = text.substring(0, lineStart) + 
                       text.substring(lineEnd === -1 ? text.length : lineEnd + 1)

        this.editor.editor.value = newText
        this.editor.editor.selectionStart = this.editor.editor.selectionEnd = lineStart
        this.editor._updateEditor()
    }

    /**
     * 复制行
     */
    duplicateLine() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lineStart = text.lastIndexOf('\n', pos - 1) + 1
        const lineEnd = text.indexOf('\n', pos)

        const line = text.substring(lineStart, lineEnd === -1 ? text.length : lineEnd)
        const newText = text.substring(0, lineEnd === -1 ? text.length : lineEnd) + 
                       '\n' + line + 
                       text.substring(lineEnd === -1 ? text.length : lineEnd)

        this.editor.editor.value = newText
        this.editor.editor.selectionStart = this.editor.editor.selectionEnd = pos + line.length + 1
        this.editor._updateEditor()
    }

    /**
     * 上移行
     */
    moveLineUp() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lines = text.split('\n')
        const currentLineIndex = text.substring(0, pos).split('\n').length - 1

        if (currentLineIndex > 0) {
            // 交换行
            [lines[currentLineIndex - 1], lines[currentLineIndex]] = 
                [lines[currentLineIndex], lines[currentLineIndex - 1]]

            this.editor.editor.value = lines.join('\n')

            // 调整光标位置
            const newPos = pos - lines[currentLineIndex].length - 1
            this.editor.editor.selectionStart = this.editor.editor.selectionEnd = newPos

            this.editor._updateEditor()
            return true
        }
        return false
    }

    /**
     * 下移行
     */
    moveLineDown() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lines = text.split('\n')
        const currentLineIndex = text.substring(0, pos).split('\n').length - 1

        if (currentLineIndex < lines.length - 1) {
            // 交换行
            [lines[currentLineIndex], lines[currentLineIndex + 1]] = 
                [lines[currentLineIndex + 1], lines[currentLineIndex]]

            this.editor.editor.value = lines.join('\n')

            // 调整光标位置
            const newPos = pos + lines[currentLineIndex].length + 1
            this.editor.editor.selectionStart = this.editor.editor.selectionEnd = newPos

            this.editor._updateEditor()
            return true
        }
        return false
    }

    /**
     * 在上方插入行
     */
    insertLineAbove() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lineStart = text.lastIndexOf('\n', pos - 1) + 1

        this.editor.editor.value = text.substring(0, lineStart) + '\n' + text.substring(lineStart)
        this.editor.editor.selectionStart = this.editor.editor.selectionEnd = lineStart
        this.editor._updateEditor()
    }

    /**
     * 在下方插入行
     */
    insertLineBelow() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lineEnd = text.indexOf('\n', pos)
        const insertPos = lineEnd === -1 ? text.length : lineEnd

        this.editor.editor.value = text.substring(0, insertPos) + '\n' + text.substring(insertPos)
        this.editor.editor.selectionStart = this.editor.editor.selectionEnd = insertPos + 1
        this.editor._updateEditor()
    }

    /**
     * 切换行注释
     */
    toggleLineComment() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lineStart = text.lastIndexOf('\n', pos - 1) + 1
        const lineEnd = text.indexOf('\n', pos)
        const line = text.substring(lineStart, lineEnd === -1 ? text.length : lineEnd)

        let newLine
        if (line.trim().startsWith('//')) {
            // 移除注释
            newLine = line.replace(/^(\s*)\/\/\s?/, '$1')
        } else {
            // 添加注释
            const indent = line.match(/^\s*/)[0]
            newLine = indent + '// ' + line.substring(indent.length)
        }

        this.editor.editor.value = text.substring(0, lineStart) + newLine + 
                                  text.substring(lineEnd === -1 ? text.length : lineEnd)

        this.editor.editor.selectionStart = this.editor.editor.selectionEnd = pos
        this.editor._updateEditor()
    }

    /**
     * 切换块注释
     */
    toggleBlockComment() {
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd
        const selectedText = this.editor.editor.value.substring(start, end)

        let newText
        if (selectedText.startsWith('/*') && selectedText.endsWith('*/')) {
            // 移除块注释
            newText = selectedText.substring(2, selectedText.length - 2)
        } else {
            // 添加块注释
            newText = '/*' + selectedText + '*/'
        }

        this.editor.editor.value = this.editor.editor.value.substring(0, start) + 
                                  newText + 
                                  this.editor.editor.value.substring(end)

        this.editor.editor.selectionStart = start
        this.editor.editor.selectionEnd = start + newText.length
        this.editor._updateEditor()
    }

    /**
     * 转换为大写
     */
    transformToUppercase() {
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd

        if (start !== end) {
            const selectedText = this.editor.editor.value.substring(start, end)
            const upperText = selectedText.toUpperCase()

            this.editor.editor.value = this.editor.editor.value.substring(0, start) + 
                                      upperText + 
                                      this.editor.editor.value.substring(end)

            this.editor.editor.selectionStart = start
            this.editor.editor.selectionEnd = start + upperText.length
            this.editor._updateEditor()
            return true
        }
        return false
    }

    /**
     * 转换为小写
     */
    transformToLowercase() {
        const start = this.editor.editor.selectionStart
        const end = this.editor.editor.selectionEnd

        if (start !== end) {
            const selectedText = this.editor.editor.value.substring(start, end)
            const lowerText = selectedText.toLowerCase()

            this.editor.editor.value = this.editor.editor.value.substring(0, start) + 
                                      lowerText + 
                                      this.editor.editor.value.substring(end)

            this.editor.editor.selectionStart = start
            this.editor.editor.selectionEnd = start + lowerText.length
            this.editor._updateEditor()
            return true
        }
        return false
    }

    /**
     * 选中当前行
     */
    selectLine() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart
        const lineStart = text.lastIndexOf('\n', pos - 1) + 1
        const lineEnd = text.indexOf('\n', pos)

        this.editor.editor.selectionStart = lineStart
        this.editor.editor.selectionEnd = lineEnd === -1 ? text.length : lineEnd
    }

    /**
     * 选中光标位置的单词
     */
    selectWordAtCursor() {
        const text = this.editor.editor.value
        const pos = this.editor.editor.selectionStart

        // 向前找单词边界
        let start = pos
        while (start > 0 && /\w/.test(text[start - 1])) {
            start--
        }

        // 向后找单词边界
        let end = pos
        while (end < text.length && /\w/.test(text[end])) {
            end++
        }

        if (start < end) {
            this.editor.editor.selectionStart = start
            this.editor.editor.selectionEnd = end
            return true
        }
        return false
    }

    /**
     * 更新配置
     * @param {Object} newOptions - 新的配置选项
     */
    updateOptions(newOptions) {
        this.options = { ...this.options, ...newOptions }
    }
}